package adminloginterceptor

import (
	"context"
	"encoding/json"
	"github.com/go-playground/validator"
	"vpn-management-server/logger"
	"vpn-management-server/network"
	"vpn-management-server/security/code"
	"vpn-management-server/src/model/adminlogmodel"
	"vpn-management-server/src/model/adminmodel"
	"vpn-management-server/src/service/adminservice"
)

func AdminLogsValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	var adminLogJson adminlogmodel.AdminLogJson
	// 待研究
	err := json.Unmarshal([]byte(request.Parameters), &adminLogJson)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "UnMarshal Parameters to adminLogJson error,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "parse parameters fail"
		return false
	}
	valid := validator.New()
	err = valid.Struct(adminLogJson)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "validate Parameters fail,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "validate parameters fail"
		return false
	}
	if rank := adminservice.GetAdminRankService(ctx, request, response); rank == adminmodel.SuperAdmin || rank == adminmodel.RuleAdmin {
		request.SetModel(&adminLogJson)
		return true
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "have no authority")
		response.Code = code.UNAUTHORIZED
		response.ErrorMsg = "have no authority"
		return false
	}
}

func AdminLogsIDValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	var adminLogIDJson adminlogmodel.AdminLogIDJson
	err := json.Unmarshal([]byte(request.Parameters), &adminLogIDJson)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "UnMarshal Parameters to adminLogIDJson error,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "parse parameters fail"
		return false
	}
	valid := validator.New()
	err = valid.Struct(adminLogIDJson)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "validate Parameters fail,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "validate parameters fail"
		return false
	}
	if rank := adminservice.GetAdminRankService(ctx, request, response); rank == adminmodel.SuperAdmin || rank == adminmodel.RuleAdmin {
		request.SetModel(&adminLogIDJson)
		return true
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "have no authority")
		response.Code = code.UNAUTHORIZED
		response.ErrorMsg = "have no authority"
		return false
	}
}
